package api

import (
	"context"
	"time"

	"github.com/docker/docker/api/types"
	"github.com/docker/docker/client"
	"github.com/gin-gonic/gin"
)

func ContainerList(c *gin.Context) {
	ctx := context.Background()
	cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
	if err != nil {
		panic(err)
	}
	options := types.ContainerListOptions{}
	options.All = true
	containerList, err := cli.ContainerList(ctx, options)
	if err != nil {
		panic(err)
	}

	c.JSON(200, gin.H{"code": 0, "message": "容器列表", "data": containerList})
}

func ContainerRemove(c *gin.Context) {
	containerId := c.Query("containerId")
	ctx := context.Background()
	cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
	if err != nil {
		panic(err)
	}
	options := types.ContainerRemoveOptions{}
	err = cli.ContainerRemove(ctx, containerId, options)
	if err != nil {
		c.JSON(200, gin.H{"code": 1, "message": "容器删除失败"})
		return
	}

	c.JSON(200, gin.H{"code": 0, "message": "容器删除成功"})
}

func ContainerStart(c *gin.Context) {
	containerId := c.Query("containerId")
	ctx := context.Background()
	cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
	if err != nil {
		panic(err)
	}
	options := types.ContainerStartOptions{}
	err = cli.ContainerStart(ctx, containerId, options)
	if err != nil {
		c.JSON(200, gin.H{"code": 1, "message": "容器启动失败"})
		return
	}

	c.JSON(200, gin.H{"code": 0, "message": "容器启动成功"})
}

func ContainerStop(c *gin.Context) {
	containerId := c.Query("containerId")
	ctx := context.Background()
	cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
	if err != nil {
		panic(err)
	}

	var duration_Milliseconds time.Duration = 500 * time.Millisecond
	err = cli.ContainerStop(ctx, containerId, &duration_Milliseconds)
	if err != nil {
		c.JSON(200, gin.H{"code": 1, "message": "容器停止失败"})
		return
	}

	c.JSON(200, gin.H{"code": 0, "message": "容器停止成功"})
}

func ContainerRestart(c *gin.Context) {
	containerId := c.Query("containerId")
	ctx := context.Background()
	cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
	if err != nil {
		panic(err)
	}

	var duration_Milliseconds time.Duration = 5000 * time.Millisecond
	err = cli.ContainerRestart(ctx, containerId, &duration_Milliseconds)
	if err != nil {
		c.JSON(200, gin.H{"code": 1, "message": "容器重启失败"})
		return
	}

	c.JSON(200, gin.H{"code": 0, "message": "容器重启成功"})
}
